﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lidgren.Network;
using System.Threading;

namespace TestcraftLibrary.Network
{
    public class NetworkHandler
    {
        public NetClient client;
        private Thread readThread;
        public event EventHandler<MessageReceivedEventArgs> MessageReceived;

        public NetworkHandler(Lidgren.Network.NetClient netClient)
        {
            this.client = netClient;
            this.readThread = new Thread(this.readLoop);
            this.readThread.IsBackground = true;
            this.readThread.Start();
        }

        private void readLoop()
        {
            while (true)
            {
                this.client.MessageReceivedEvent.WaitOne();
                NetIncomingMessage message = this.client.ReadMessage();
                MessageType type = (MessageType)message.ReadByte();

                this.OnMessageReceived(new MessageReceivedEventArgs(type, message));
            }
        }

        private void OnMessageReceived(MessageReceivedEventArgs e)
        {
            if (this.MessageReceived != null)
                this.MessageReceived.BeginInvoke(this, e, this.OnMessageReceivedCallback, null);
        }

        private void OnMessageReceivedCallback(IAsyncResult result)
        {
            this.MessageReceived.EndInvoke(result);
        }


    }
}
